import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/smart-import',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' },
  },
  {
    path: '/password-reset',
    name: 'PasswordReset',
    component: () => import('@/views/PasswordReset.vue'),
    meta: { title: '重置密码' },
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '数据看板', icon: 'DataAnalysis' },
      },
      {
        path: 'leads',
        name: 'Leads',
        component: () => import('@/views/leads/LeadList.vue'),
        meta: { title: '客户管理', icon: 'User' },
      },
      {
        path: 'properties',
        name: 'Properties',
        component: () => import('@/views/properties/PropertyList.vue'),
        meta: { title: '房源管理', icon: 'House' },
      },
      {
        path: 'visitor-sheets',
        name: 'VisitorSheets',
        component: () => import('@/views/visitor-sheets/VisitorSheetList.vue'),
        meta: { title: '访客单管理', icon: 'Document' },
      },
      {
        path: 'tags',
        name: 'Tags',
        component: () => import('@/views/tags/TagList.vue'),
        meta: { title: '标签管理', icon: 'PriceTag' },
      },
      {
        path: 'smart-import',
        name: 'SmartImport',
        component: () => import('@/views/SmartImport.vue'),
        meta: { title: '⚡ 智能导入', icon: 'MagicStick' },
      },
      {
        path: 'import',
        name: 'Import',
        component: () => import('@/views/Import.vue'),
        meta: { title: 'Excel导入', icon: 'Upload' },
      },
      {
        path: 'import-audit/:batchId',
        name: 'ImportAudit',
        component: () => import('@/views/import-audit/ImportAuditPage.vue'),
        meta: { title: '导入审核', icon: 'Check' },
      },
      {
        path: 'import-history',
        name: 'ImportHistory',
        component: () => import('@/views/ImportHistory.vue'),
        meta: { title: '导入历史', icon: 'Clock' },
      },
      {
        path: 'test-interaction',
        name: 'TestInteraction',
        component: () => import('../tests/TestInteractionView.vue'),
        meta: { title: '交互测试', icon: 'Bug', public: true },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  const token = localStorage.getItem('token')
  const isPublic = to.matched.some(r => (r.meta as Record<string, unknown>)?.public === true)
  const publicPaths = ['/login', '/password-reset']
  if (!token && !isPublic && !publicPaths.includes(to.path)) {
    next('/login')
  } else {
    next()
  }
})

export default router
